<template>
  <div class="app-container">
    <div class="filter-container" style="padding-bottom: 25px">
      <el-input v-model="listQuery.username" placeholder="账号" style="width: 200px;" class="filter-item"  @keyup.enter.native="handleFilter" />

      <el-button v-waves  class="filter-item" type="primary" icon="el-icon-search" @click="getList">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate" v-permission="'add-admin'">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >


      <el-table-column label="ID" prop="id"  align="center" width="80" >
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户名称" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column label="登陆次数" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.last_count }}</span>
        </template>
      </el-table-column>


      <el-table-column label="上次登陆时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.last_at }}</span>
        </template>
      </el-table-column>

      <el-table-column label="上次登陆IP" align="center">
        <template slot-scope="{row}">
          <span>{{ row.last_ip }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="260" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" v-if="row.username!='admin'" size="mini" @click="handleUpdate(row)" v-permission="'edit-admin'">
            编辑
          </el-button>

          <el-button v-if="row.username!='admin'" size="mini" type="danger" @click="handleModifyStatus(row)" v-permission="'delete-admin'">
            删除
          </el-button>

          <el-button v-if="row.username!='admin'" size="mini" type="danger" @click="handlePermission(row)" v-permission="'distribution-permission'">
            分配权限
          </el-button>

        </template>
      </el-table-column>
    </el-table>


    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />


    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">

      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="账号" prop="username">
          <el-input v-model="temp.username" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>


    <el-dialog title="分配权限" :visible.sync="dialogFormVisiblePermission">

      <el-form ref="dataFormPermission" :rules="rules" :model="temp" label-position="left" label-width="50%" style="width: 400px; margin-left:50px;">
        <el-tree
          :data="data"
          show-checkbox
          node-key="id"
          ref="tree"
          :default-checked-keys=checked_keys
          :check-on-click-node="true"
          :default-expand-all="true"
          :props="defaultProps">
        </el-tree>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisiblePermission = false">
          取消
        </el-button>
        <el-button type="primary" @click="setPermission">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>
    import { adminsList, createAdmin, updateAdmin, deleteAdmin,getPermissions,setPermissions } from '@/api/admins'
    import Pagination from '@/components/Pagination' // secondary package based on el-pagination

    export default {
        name: 'admins',

        components: { Pagination },

        data(){
            return {
              data: [],
              checked_keys:[],
              defaultProps: {
                children: 'children',
                label: 'name'
              },
                total:0,
                tableKey:0,
                listLoading: true,
                list: null,

                listQuery: {
                    page: 1,
                    limit: 20,
                    username: undefined,
                },
                importanceOptions: [1, 2, 3],
                dialogFormVisible:false,
                dialogFormVisiblePermission:false,
                rules: {
                    username: [{ required: true, message: '账号必填', trigger: 'blur' }],
                    password: [{ required: true, message: '密码必填', trigger: 'blur' }]
                },
                dialogStatus: '',
                textMap: {
                    update: '编辑',
                    create: '添加'
                },
                temp: {
                    id: undefined,
                    username: '',
                    password: ''
                },
              row:{},
            }
        },

        created() {
            this.getList()
        },
        methods:{
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },

            setPermission(){
              var keys = this.$refs.tree.getCheckedKeys(false);


              if (keys.length == 0){

                this.$notify({
                  title: '',
                  message: '请选择节点',
                  type: 'error',
                  duration: 2000
                })
                return;
              }

              var id = this.row.id;

              const p = {ids:keys,id:id};

              setPermissions(p).then(() => {

                this.getList();

                this.dialogFormVisiblePermission = false
                this.$notify({
                  title: '',
                  message: '设置管理员权限成功',
                  type: 'success',
                  duration: 1500
                })
              })

            },

            //  分配权限
            handlePermission(row) {

              //  获取数据
              getPermissions({id:row.id}).then(response => {
                this.data = response.data.all_permission;
                this.checked_keys = response.data.checked_permission;

                this.dialogFormVisiblePermission = true;

                this.row = row;
              })
            },

            handleModifyStatus(row) {
                this.$confirm('确定删除该管理员吗', 'Warning', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(async() => {

                        await deleteAdmin({id:row.id})
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        })

                         await this.getList();
                    })
                    .catch(err => {

                    })

            },
            handleUpdate(row) {
                this.temp = Object.assign({}, row) // copy obj
                this.temp.password = '';

                this.dialogStatus = 'update'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            getList() {
                this.listLoading = true
                adminsList(this.listQuery).then(response => {

                    this.list = response.data.items
                    this.total = response.data.total

                    setTimeout(() => {
                        this.listLoading = false
                    }, 0.5 * 1000)
                })
            },

            handleCreate() {
                this.resetTemp()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            resetTemp() {
                this.temp = {
                    'username':'',
                    'password':''
                }
            },
            createData(){
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
                        createAdmin(this.temp).then(() => {
                            // this.list.unshift(this.temp)
                            this.dialogFormVisible = false
                            this.$notify({
                                title: '',
                                message: '添加管理员成功',
                                type: 'success',
                                duration: 2000
                            })

                             this.getList();

                        })
                    }
                })
            },
            updateData(){
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        const tempData = Object.assign({}, this.temp)

                        const cc = {username:tempData.username,password:tempData.password,id:tempData.id}
                        updateAdmin(cc).then(() => {

                            this.getList();

                            this.dialogFormVisible = false
                            this.$notify({
                                title: '',
                                message: '更新管理员成功',
                                type: 'success',
                                duration: 2000
                            })
                        })
                    }
                })
            }
        }
    }
</script>
